<?php
/**
 * 
 * @author	ronnie  (comdeng@gmail.com)
 * @link		http://fillphp.com/
 * @date		2014-5-3 下午10:13:28
 * @file		Helper.php
 * @description 
 */
namespace fillphp\helper;

class Helper
{
	/**
	 * @var \fillphp\page\Request
	 */
	protected $request;
	
	/**
	 * @var \fillphp\view\View
	 */
	protected $view;
	
	private static $helperDirs = array(
		__NAMESPACE__ => __DIR__,			
	);
	
	private static $helpers = array();
	
	/**
	 * 
	 * @param \fillphp\page\Request $request
	 */
	function setRequest($request)
	{
		$this->request = $request;
	}
	
	/**
	 * 
	 * @param \fillphp\view\View $view
	 */
	function setView($view)
	{
		$this->view = $view;
	}
	
	/**
	 * 添加帮助器目录
	 * @param string $dir 目录
	 * @param string $ns 命名空间
	 */
	static function addHelperDir($dir, $ns)
	{
		self::$helperDirs[$ns] = $dir;
	}
	
	/**
	 * 获取帮助器
	 * @param string $name
	 * @param \fillphp\page\Request $request
	 * @return \fillphp\helper\Helper | false
	 */
	static function getHelper($name, $request = NULL)
	{
		if (isset(self::$helpers[$name])) {
			if ($request) {
				self::$helpers[$name]->setRequest($request);
			}
			return self::$helpers[$name];
		}
		
		foreach(self::$helperDirs as $ns => $dir) {
			$path = $dir.'/'.ucfirst($name).'.php';
			if (is_readable($path)) {
				$cls = $ns.'\\'.ucfirst($name);
				require_once $path;
				if (!class_exists($cls)) {
					throw new \Exception(__NAMESPACE__.':helperNotDefined class:'.$cls);
				}
				return self::$helpers[$name] = new $cls();
			}
		}
		throw new \Exception(__NAMESPACE__.':helperNotFound helper:'.$name);
	}
}
